package gitee

import (
	"fmt"
	"net/http"
	"os"
	"strconv"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis"
)

func Login(c *gin.Context) {
	c.HTML(http.StatusOK, "login.html", gin.H{
		"ClientId":    client.ClientId,
		"RedirectUrl": client.RedirectUrl,
	})
}

func Passport(c *gin.Context) {
	code := c.DefaultQuery("code", "")
	if code == "" {
		c.HTML(http.StatusBadRequest, "4XX.html", gin.H{"detail": "无效URL链接！"})
		return
	}

	accessToken, err := GetAccessToken(code)
	if err != nil {
		c.HTML(http.StatusBadRequest, "4XX.html", gin.H{"detail": "错误请求！"})
		return
	}

	userInfo, err := GetUserInfo(accessToken)
	if err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
	}

	// 保存用户信息到数据库
	if err := userInfo.SaveUser(); err != nil {
		// TODO: logging
		c.HTML(http.StatusInternalServerError, "500.html", gin.H{"detail": "服务错误！管理人员正在解决..."})
		return
	}

	// 保存session信息
	session := sessions.Default(c)
	session.Options(sessions.Options{MaxAge: 14 * 3600})

	userId := strconv.Itoa(userInfo.ID)
	if session.Get("user_id") != userId {
		session.Set("user_id", userId)
		session.Save()
	}

	c.Redirect(http.StatusFound, "/auth/profile/")
}

func Profile(c *gin.Context) {
	session := sessions.Default(c)
	userId := session.Get("user_id")

	if userId == nil {
		c.Redirect(http.StatusFound, "/")
		return
	}

	userInfo, err := GetUserByUserId(fmt.Sprintf("%v", userId))

	if err != nil {
		c.HTML(http.StatusInternalServerError, "500.html", gin.H{"detail": "服务错误！管理人员正在解决..."})
	}

	contents := gin.H{
		"username":   userInfo.Login,
		"name":       userInfo.Name,
		"avatar_url": userInfo.AvatarUrl,
	}

	c.HTML(http.StatusOK, "profile.html", contents)
}

func Logout(c *gin.Context) {
	session := sessions.Default(c)
	userId := session.Get("user_id")

	// 删除session信息
	session.Delete("user_id")
	session.Save()

	if userId == nil {
		c.Redirect(http.StatusFound, "/")
		return
	}

	strUserId := fmt.Sprintf("%v", userId)
	id, err := rdb.HGet("userinfo:user-id", strUserId).Result()

	if err == redis.Nil || err != nil {
		c.Redirect(http.StatusFound, "/")
		return
	}

	// 删除redis信息
	pipe := rdb.Pipeline()
	// 键 userinfo:1 属于一个用户所有
	pipe.Del("userinfo:" + id)
	//  键 userinfo:user-id 属于所有用户所有,只需要删除该userId对应的键值对即可
	pipe.HDel("userinfo:user-id", strUserId)
	// 不管返回的err是否为nil都重定向到主页
	pipe.Exec()

	c.Redirect(http.StatusFound, "/")
}
